package com.slwish.xty.ui.activity;

import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.slwish.common.base.PresenterNoToolbarActivity;
import com.slwish.common.config.Contants;
import com.slwish.common.interf.PerfectClickListener;
import com.slwish.common.utils.IntentUtils;
import com.slwish.common.utils.SpUtils;
import com.slwish.common.utils.StatusBarUtils;
import com.slwish.common.utils.StringUtils;
import com.slwish.xty.R;
import com.slwish.xty.adapter.MainAdapter;
import com.slwish.xty.config.GlideImageLoader;
import com.slwish.xty.db.UserDb;
import com.slwish.xty.entity.CreditTourismInfoModel;
import com.slwish.xty.entity.MainBannerModel;
import com.slwish.xty.entity.UserModel;
import com.slwish.xty.mvp.contract.MainContract;
import com.slwish.xty.mvp.presenter.MainPresenter;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class MainActivity extends PresenterNoToolbarActivity<MainContract.Presenter> implements MainContract.View, XRecyclerView.LoadingListener {
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.xrecyclerview)
    XRecyclerView xrecyclerview;
    @BindView(R.id.toolba)
    RelativeLayout relativeLayout;
    MainAdapter mAdapter;
    List<CreditTourismInfoModel> mLists = new ArrayList<>();//列表数据集
    private Banner banner;//轮播
    private LinearLayout creditLife;//信用生活
    private LinearLayout creditLy;//信用旅游

    private long currentBackPressedTime = 0;
    // 退出间隔
    private static final int BACK_PRESSED_INTERVAL = 2000;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean isShowStatusBar() {
        return false;
    }

    @Override
    protected boolean isEventBus() {
        return true;
    }

    @Override
    protected void initWidget() {
        super.initWidget();

        View viewHead = LayoutInflater.from(this).inflate(R.layout.inclue_main_header, (ViewGroup) findViewById(android.R.id.content), false);
        banner = getView(viewHead, R.id.banner);
        creditLife = getView(viewHead, R.id.rl_credit_life);
        creditLy = getView(viewHead, R.id.rl_credit_ly);
        //设置Banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR).setIndicatorGravity(BannerConfig.CENTER);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader()).start();
        xrecyclerview.setLayoutManager();
        mAdapter = new MainAdapter(mLists);
        mAdapter.addHeaderView(viewHead);
        xrecyclerview.setAdapter(mAdapter);
        mPresenter.getBannerData();//获取Banner数据
        xrecyclerview.setLoadingListener(this);
        //取缓存的数据,绑定到列表。防止在首页加载时，出现空白的现象
        String main_json = (String) SpUtils.get(mContext, Contants.MAIN_JSON, "");
        try {
            if (!StringUtils.isEmpty(main_json)) {
                List<CreditTourismInfoModel> list = JSON.parseArray(main_json, CreditTourismInfoModel.class);
                getMainListDataSuccess(list);
            } else {
                xrecyclerview.refresh();
            }
        } catch (Exception e) {
        }
        long userCode = SpUtils.getLong(mContext, Contants.UserCode, 0);
        if (userCode > 0) {
            UserModel userModel = UserDb.query(userCode + "");
            setHeadInfo(userModel);
        }
    }

    /**
     * 设置侧拉栏头部信息
     *
     * @param userModel 用户信息
     */
    private void setHeadInfo(UserModel userModel) {
        if (userModel != null) {
            long userid = SpUtils.getLong(mContext, Contants.UserCode, 0);
            tvLogin.setText(userid > 0 ? (StringUtils.isEmpty(userModel.getNickname()) ? "昵称" : userModel.getNickname()) : "登录/注册");
            RequestOptions options = RequestOptions.circleCropTransform()
                    .placeholder(R.mipmap.touxiang88)
                    .error(R.mipmap.touxiang88);
            if (userModel.getPhoto() == null || userModel.getPhoto().equals("")) {
                ivHeader.setImageResource(R.mipmap.touxiang88);
            } else {
                Glide.with(mContext)
                        .load(userModel.getPhoto())
                        .apply(options)
                        .into(ivHeader);
            }
        } else {
            ivHeader.setImageResource(R.mipmap.touxiang88);
            tvLogin.setText("登录/注册");
        }
    }

    /**
     * 监听返回按钮
     */
    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
//            super.onBackPressed();
            // 判断时间间隔
            if ((System.currentTimeMillis() - currentBackPressedTime) > BACK_PRESSED_INTERVAL) {
                currentBackPressedTime = System.currentTimeMillis();
                showError(R.string.click_again);
            } else {
                // 退出
                finish();
            }
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        xrecyclerview.setScrollAlphaChangeListener(new XRecyclerView.ScrollAlphaChangeListener() {
            @Override
            public void onAlphaChange(int alpha) {
//                if (alpha > 0) {
//                    immersionBar(getResources().getColor(R.color.colorAccent), 255 - alpha);
                    StatusBarUtils.setColorForDrawerLayout(MainActivity.this,drawerLayout,   getResources().getColor(R.color.colorAccent),255-alpha);
//                    StatusBarUtils.setColor(MainActivity.this, getResources().getColor(R.color.colorAccent), 255 - alpha);
//                } else {
                    StatusBarUtils.setTransparentForWindow(MainActivity.this);
//                }
                relativeLayout.getBackground().setAlpha(alpha);
            }

            @Override
            public int setLimitHeight() {
                return 300;
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt(Contants.ID, mAdapter.getItem(position - 1).getMerId());
                bundle.putSerializable(Contants.MODEL, mAdapter.getItem(position - 1));
                IntentUtils.startActivity(mContext, CreditTourismInfoActivity.class, bundle);
            }
        });
        //信用生活
        creditLife.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                IntentUtils.startActivity(mContext, CreditLifeActivity.class);
            }
        });
        //信用旅游
        creditLy.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                IntentUtils.startActivity(mContext, CreditTourismListActivity.class);
            }
        });
    }

    @OnClick({R.id.iv_user, R.id.iv_header, R.id.tv_login, R.id.tv_search, R.id.tv_yy, R.id.tv_pj, R.id.tv_ts, R.id.tv_jf, R.id.iv_scan, R.id.iv_map})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_header:
            case R.id.tv_login://登录
                checkIntent(UserInfoActivity.class);
//                IntentUtils.startActivity(mContext, LoginActivity.class);
                break;
            case R.id.iv_user://用户
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.tv_search://搜索
                IntentUtils.startActivity(mContext, SearchListActivity.class);
                break;
            case R.id.iv_scan://扫描
                IntentUtils.startActivity(mContext, ScanActivity.class);
                break;
            case R.id.tv_yy://我的预约
                checkIntent(SubscribeListActivity.class);
                break;
            case R.id.tv_pj://我的评价
                checkIntent(MyCommentListActivity.class);
                break;
            case R.id.tv_ts://我的投诉
                checkIntent(MyComplaintListActivity.class);
                break;
            case R.id.tv_jf://我的信用分
                checkIntent(MyCreditPointsActivity.class);
                break;
            case R.id.iv_map://地图
                IntentUtils.startActivity(mContext, MapActivity.class);
                break;
        }
    }

    /**
     * 检查登录
     *
     * @param clazz
     */
    private void checkIntent(Class clazz) {
        long userId = SpUtils.getLong(mContext, Contants.UserCode, 0);
        if (userId > 0)
            IntentUtils.startActivity(mContext, clazz);
        else
            IntentUtils.startActivity(mContext, LoginActivity.class);
    }

    //绑定Presenter
    @Override
    protected MainContract.Presenter initPresenter() {
        return new MainPresenter(this);
    }

    /**
     * 轮播图数据
     *
     * @param model
     */
    @Override
    public void getBannerDataSuccess(MainBannerModel model) {
        try {
//            loadService.showSuccess();
            List<String> imageUrls = new ArrayList<>();
            for (MainBannerModel.BannerModel data : model.getData()) {
                imageUrls.add(data.getServerPath());
            }
            banner.setImages(imageUrls).start();
        } catch (Exception e) {
        }
    }

    /**
     * 首页列表数据
     *
     * @param model
     */
    @Override
    public void getMainListDataSuccess(List<CreditTourismInfoModel> model) {
        if (model != null && model.size() > 0) {
            if (mPagerCofig.getCurrentPage() == 1) {
                mLists.clear();
                xrecyclerview.refreshComplete();
            }
            mLists.addAll(model);
            xrecyclerview.setNoMore(false);
        } else {
            if (mPagerCofig.getCurrentPage() == 1) {
                //显示无数据界面
//                View view = View.inflate(mContext, R.layout.layout_empty, null);
//                mAdapter.setEmptyView(view);
//                xrecyclerview.refreshComplete();
            }
            //数据全部加载完成
            xrecyclerview.setNoMore(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        banner.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //结束轮播
        banner.stopAutoPlay();
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        mPagerCofig.setCurrentPage(1);
        mPresenter.getMainListData("119.697805", "29.70", mPagerCofig.getCurrentPage());//获取首页列表数据
    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadMore() {
        if (mAdapter.getItemCount() / 10 == mPagerCofig.getCurrentPage()) {
            mPagerCofig.setCurrentPage(1 + mPagerCofig.getCurrentPage());
            mPresenter.getMainListData("119.697805", "29.70", mPagerCofig.getCurrentPage());//获取首页列表数据
        } else {
            xrecyclerview.setNoMore(true);
        }
    }

    /**
     * 关闭侧边栏
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void closerDrawer(String messageEvent) {
        if (messageEvent.equals("closeDrawer"))
            drawerLayout.closeDrawer(GravityCompat.START);
    }

    /**
     * 刷新侧边栏头部信息
     *
     * @param userModel
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void bindingUserInfo(UserModel userModel) {
        setHeadInfo(userModel);
    }// 退出时间

}
